package cn.net.qinling.healthcare;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.openhealthtools.mdht.uml.cda.ccd.ContinuityOfCareDocument;
import org.openhealthtools.mdht.uml.cda.util.CDAUtil;

import cn.net.qinling.healthcare.test.datagen.ExcelFileSelector;
import cn.net.qinling.healthcare.test.datagen.PrescriptionGenerator;
import cn.net.qinling.healthcare.test.datagen.Selector;

public class Main {

	private static final int totalCount = 500000;

	private static String outputPath = "e:\\cda\\";

	private static final int maxCountPerFolder = 2000;

	private static final SimpleDateFormat timestampFormat = new SimpleDateFormat(
			"yyyymmddhhMMss");

	private static File outputDir = null;

	private static boolean initOutputDir(int genCount) {
		Date currentTime = new Date();
		outputPath = outputPath + timestampFormat.format(currentTime) + "_"
				+ genCount + File.separator;
		outputDir = new File(outputPath);
		if (!outputDir.exists()) {
			outputDir.mkdir();
		}

		return outputDir.isDirectory() && outputDir.canWrite();
	}

	private static boolean initSubDir(int id) {
		if (id > maxCountPerFolder) {
			return false;
		}
		File subDir = new File(outputPath + id);
		if (!subDir.exists()) {
			subDir.mkdir();
		} else {
			return initSubDir(id + 1);
		}

		return subDir.isDirectory() && subDir.canWrite();
	}

	public static void main(String[] args) {

		if (!initOutputDir(totalCount)) {
			System.err.println("Output directory is not ready! Exit!");
			return;
		}

		try {
			Selector selector = ExcelFileSelector.getSelector("e:\\codes.xls");

			PrescriptionGenerator pg = new PrescriptionGenerator(selector);

			int subFolderId = 0;
			for (int i = 0; i < totalCount; i++) {
				System.out.println("Generating " + i + " ...");
				if (i % maxCountPerFolder == 0) {
					subFolderId = i / maxCountPerFolder;
					initSubDir(subFolderId);
				}

				ContinuityOfCareDocument doc = pg.generate();
				String fileName = doc.getId().getExtension()
						.replaceAll("-", "");
				String filePath = outputPath + File.separator + subFolderId
						+ File.separator + fileName;
				FileOutputStream fos = new FileOutputStream(filePath);

				CDAUtil.save(doc, fos);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
